package com.java.springcloud.controller;

import com.java.springcloud.RedisMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("setZet")
    public void setZet(@RequestBody RedisMap map) {
        redisTemplate.executePipelined(new RedisCallback<List>() {
            @Override
            public List doInRedis(RedisConnection connection) throws DataAccessException {

                for (int i = 0; i < 100000; i++) {
                    StringBuffer sb = new StringBuffer("ceshi");
                    sb.append(i);
                    connection.zAdd("name".getBytes(), i, sb.toString().getBytes());
                }
                return null;
            }
        });
    }

    @PostMapping("getZet")
    public Set getZet(@RequestBody RedisMap map) {
        return redisTemplate.opsForZSet().rangeWithScores(map.getKey(), 0, -1);
    }

    @PostMapping("del")
    public void del(@RequestBody RedisMap map) {
        redisTemplate.delete(map.getKey());
    }
}